import React, { useState } from 'react';
import {
  Card,
  Row,
  Col,
  Typography,
  Button,
  Input,
  Modal,
  Form,
  Statistic,
  List,
  Tag,
  Space,
  Alert,
  Tabs,
  Progress,
  message,
  Tooltip
} from 'antd';
import {
  BankOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  TrophyOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  WalletOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { useWallet } from '../contexts/WalletContext';
import { useQuery, useMutation, useQueryClient } from 'react-query';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

const Staking = () => {
  const [stakeAmount, setStakeAmount] = useState('');
  const [unstakeAmount, setUnstakeAmount] = useState('');
  const [selectedStakeId, setSelectedStakeId] = useState(null);
  const [isStakeModalVisible, setIsStakeModalVisible] = useState(false);
  const [isUnstakeModalVisible, setIsUnstakeModalVisible] = useState(false);
  const [claimingInterest, setClaimingInterest] = useState(false);

  const { apiCall } = useAuth();
  const { sendTransaction, account } = useWallet();
  const queryClient = useQueryClient();

  // Fetch user balance
  const { data: balance } = useQuery(
    'userBalance',
    () => apiCall('GET', '/users/balance'),
    { refetchInterval: 30000 }
  );

  // Fetch staking records
  const { data: stakingData } = useQuery(
    'stakingRecords',
    () => apiCall('GET', '/staking/records'),
    { refetchInterval: 30000 }
  );

  // Fetch available interest
  const { data: interestData } = useQuery(
    'availableInterest',
    () => apiCall('GET', '/staking/interest'),
    { refetchInterval: 30000 }
  );

  // Stake tokens mutation
  const stakeMutation = useMutation(
    (amount) => apiCall('POST', '/staking/stake', { amount }),
    {
      onSuccess: () => {
        message.success('Tokens staked successfully!');
        setStakeAmount('');
        setIsStakeModalVisible(false);
        queryClient.invalidateQueries('userBalance');
        queryClient.invalidateQueries('stakingRecords');
      },
      onError: (error) => {
        message.error(error.response?.data?.error || 'Staking failed');
      }
    }
  );

  // Unstake tokens mutation
  const unstakeMutation = useMutation(
    ({ stakingId, amount }) => apiCall('POST', '/staking/unstake', { stakingId, amount }),
    {
      onSuccess: () => {
        message.success('Tokens unstaked successfully!');
        setUnstakeAmount('');
        setSelectedStakeId(null);
        setIsUnstakeModalVisible(false);
        queryClient.invalidateQueries('userBalance');
        queryClient.invalidateQueries('stakingRecords');
      },
      onError: (error) => {
        message.error(error.response?.data?.error || 'Unstaking failed');
      }
    }
  );

  // Claim interest mutation
  const claimInterestMutation = useMutation(
    (interestIds) => apiCall('POST', '/staking/claim-interest', { interestIds }),
    {
      onSuccess: (data) => {
        message.success(`Claimed ${data.amount} GOD tokens!`);
        queryClient.invalidateQueries('userBalance');
        queryClient.invalidateQueries('availableInterest');
      },
      onError: (error) => {
        message.error(error.response?.data?.error || 'Claim failed');
      }
    }
  );

  const handleStake = () => {
    if (!stakeAmount || parseFloat(stakeAmount) <= 0) {
      message.error('Please enter a valid amount');
      return;
    }

    if (parseFloat(stakeAmount) > parseFloat(balance?.available_balance || 0)) {
      message.error('Insufficient balance');
      return;
    }

    stakeMutation.mutate(stakeAmount);
  };

  const handleUnstake = () => {
    if (!unstakeAmount || parseFloat(unstakeAmount) <= 0) {
      message.error('Please enter a valid amount');
      return;
    }

    if (!selectedStakeId) {
      message.error('Please select a stake to unstake from');
      return;
    }

    unstakeMutation.mutate({
      stakingId: selectedStakeId,
      amount: unstakeAmount
    });
  };

  const handleClaimInterest = async () => {
    if (!interestData?.interest || interestData.interest.length === 0) {
      message.info('No interest available to claim');
      return;
    }

    setClaimingInterest(true);
    try {
      const interestIds = interestData.interest.map(item => item.id);
      await claimInterestMutation.mutateAsync(interestIds);
    } finally {
      setClaimingInterest(false);
    }
  };

  const formatNumber = (num, decimals = 2) => {
    if (!num) return '0';
    return parseFloat(num).toFixed(decimals);
  };

  const getInterestStatus = (claimDeadline, isClaimed) => {
    if (isClaimed) return { status: 'claimed', color: 'default', text: 'Claimed' };

    const now = new Date();
    const deadline = new Date(claimDeadline);

    if (now > deadline) {
      return { status: 'expired', color: 'red', text: 'Expired' };
    }

    const hoursLeft = Math.floor((deadline - now) / (1000 * 60 * 60));
    if (hoursLeft < 1) {
      return { status: 'urgent', color: 'orange', text: 'Expiring Soon' };
    }

    return { status: 'available', color: 'green', text: 'Available' };
  };

  const activeStakes = stakingData?.records?.filter(stake => stake.status === 'active') || [];
  const completedStakes = stakingData?.records?.filter(stake => stake.status === 'completed') || [];

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <Title level={2} className="text-gray-900 mb-2">Staking</Title>
          <Text className="text-gray-600">Stake your GOD tokens to earn daily rewards</Text>
        </div>

        {/* Stats Cards */}
        <Row gutter={[16, 16]} className="mb-8">
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="Available Balance"
                value={formatNumber(balance?.available_balance)}
                prefix={<WalletOutlined />}
                suffix="GOD"
                precision={2}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="Total Staked"
                value={formatNumber(balance?.staked_balance)}
                prefix={<BankOutlined />}
                suffix="GOD"
                precision={2}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="Available Interest"
                value={formatNumber(interestData?.totalAvailable)}
                prefix={<TrophyOutlined />}
                suffix="GOD"
                precision={2}
              />
            </Card>
          </Col>
        </Row>

        {/* Staking Info */}
        <Alert
          message="Staking Information"
          description={
            <div>
              <p>• Daily Interest Rate: <strong>1%</strong></p>
              <p>• Interest Claim Deadline: <strong>1 hour</strong> after distribution</p>
              <p>• Unclaimed interest will be sent to black hole address</p>
              <p>• Minimum stake amount: <strong>100 GOD</strong></p>
            </div>
          }
          type="info"
          showIcon
          className="mb-8"
        />

        {/* Action Buttons */}
        <Row gutter={[16, 16]} className="mb-8">
          <Col xs={24} sm={8}>
            <Button
              type="primary"
              size="large"
              block
              icon={<ArrowUpOutlined />}
              onClick={() => setIsStakeModalVisible(true)}
              disabled={!balance?.available_balance || parseFloat(balance.available_balance) < 100}
            >
              Stake Tokens
            </Button>
          </Col>
          <Col xs={24} sm={8}>
            <Button
              size="large"
              block
              icon={<ArrowDownOutlined />}
              onClick={() => setIsUnstakeModalVisible(true)}
              disabled={activeStakes.length === 0}
            >
              Unstake Tokens
            </Button>
          </Col>
          <Col xs={24} sm={8}>
            <Button
              type="default"
              size="large"
              block
              icon={<TrophyOutlined />}
              onClick={handleClaimInterest}
              loading={claimingInterest}
              disabled={!interestData?.totalAvailable || parseFloat(interestData.totalAvailable) === 0}
            >
              Claim Interest
            </Button>
          </Col>
        </Row>

        {/* Staking Records */}
        <Tabs defaultActiveKey="active">
          <TabPane tab={`Active Stakes (${activeStakes.length})`} key="active">
            {activeStakes.length > 0 ? (
              <List
                dataSource={activeStakes}
                renderItem={(stake) => (
                  <List.Item>
                    <List.Item.Meta
                      title={
                        <Space>
                          <Text strong>Stake #{stake.id}</Text>
                          <Tag color="blue">Active</Tag>
                        </Space>
                      }
                      description={
                        <div>
                          <p>Amount: <strong>{formatNumber(stake.amount)} GOD</strong></p>
                          <p>Staked on: {new Date(stake.created_at).toLocaleDateString()}</p>
                          <p>Interest Rate: <strong>{(parseFloat(stake.interest_rate) * 100).toFixed(2)}% daily</strong></p>
                        </div>
                      }
                    />
                    <div>
                      <Button
                        type="primary"
                        danger
                        onClick={() => {
                          setSelectedStakeId(stake.id);
                          setUnstakeAmount(stake.amount);
                          setIsUnstakeModalVisible(true);
                        }}
                      >
                        Unstake
                      </Button>
                    </div>
                  </List.Item>
                )}
              />
            ) : (
              <div className="text-center py-8">
                <BankOutlined className="text-4xl text-gray-300 mb-4" />
                <Text type="secondary">No active stakes</Text>
              </div>
            )}
          </TabPane>

          <TabPane tab={`Completed Stakes (${completedStakes.length})`} key="completed">
            {completedStakes.length > 0 ? (
              <List
                dataSource={completedStakes}
                renderItem={(stake) => (
                  <List.Item>
                    <List.Item.Meta
                      title={
                        <Space>
                          <Text strong>Stake #{stake.id}</Text>
                          <Tag color="green">Completed</Tag>
                        </Space>
                      }
                      description={
                        <div>
                          <p>Amount: <strong>{formatNumber(stake.amount)} GOD</strong></p>
                          <p>Completed on: {new Date(stake.updated_at).toLocaleDateString()}</p>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            ) : (
              <div className="text-center py-8">
                <Text type="secondary">No completed stakes</Text>
              </div>
            )}
          </TabPane>

          <TabPane tab={`Available Interest (${interestData?.interest?.length || 0})`} key="interest">
            {interestData?.interest && interestData.interest.length > 0 ? (
              <List
                dataSource={interestData.interest}
                renderItem={(interest) => {
                  const status = getInterestStatus(interest.claim_deadline, interest.is_claimed);
                  const now = new Date();
                  const deadline = new Date(interest.claim_deadline);
                  const hoursLeft = Math.max(0, Math.floor((deadline - now) / (1000 * 60 * 60)));

                  return (
                    <List.Item>
                      <List.Item.Meta
                        title={
                          <Space>
                            <Text strong>{formatNumber(interest.interest_amount)} GOD</Text>
                            <Tag color={status.color}>{status.text}</Tag>
                          </Space>
                        }
                        description={
                          <div>
                            <p>Distribution Date: {new Date(interest.distribution_date).toLocaleDateString()}</p>
                            <p>
                              <ClockCircleOutlined />
                              {status.status === 'expired' ? ' Expired' : ` ${hoursLeft} hours left`}
                            </p>
                          </div>
                        }
                      />
                      {status.status === 'available' && (
                        <Button
                          type="primary"
                          size="small"
                          onClick={() => claimInterestMutation.mutate([interest.id])}
                          loading={claimInterestMutation.isLoading}
                        >
                          Claim
                        </Button>
                      )}
                    </List.Item>
                  );
                }}
              />
            ) : (
              <div className="text-center py-8">
                <TrophyOutlined className="text-4xl text-gray-300 mb-4" />
                <Text type="secondary">No available interest</Text>
              </div>
            )}
          </TabPane>
        </Tabs>

        {/* Stake Modal */}
        <Modal
          title="Stake Tokens"
          open={isStakeModalVisible}
          onCancel={() => {
            setIsStakeModalVisible(false);
            setStakeAmount('');
          }}
          footer={[
            <Button key="cancel" onClick={() => setIsStakeModalVisible(false)}>
              Cancel
            </Button>,
            <Button
              key="stake"
              type="primary"
              onClick={handleStake}
              loading={stakeMutation.isLoading}
            >
              Stake
            </Button>
          ]}
        >
          <Space direction="vertical" className="w-full">
            <div>
              <Text>Available Balance: {formatNumber(balance?.available_balance)} GOD</Text>
            </div>
            <Input
              type="number"
              placeholder="Enter amount to stake"
              value={stakeAmount}
              onChange={(e) => setStakeAmount(e.target.value)}
              addonAfter="GOD"
              min="100"
            />
            <Alert
              message="Minimum stake amount is 100 GOD"
              type="info"
              showIcon
            />
          </Space>
        </Modal>

        {/* Unstake Modal */}
        <Modal
          title="Unstake Tokens"
          open={isUnstakeModalVisible}
          onCancel={() => {
            setIsUnstakeModalVisible(false);
            setUnstakeAmount('');
            setSelectedStakeId(null);
          }}
          footer={[
            <Button key="cancel" onClick={() => setIsUnstakeModalVisible(false)}>
              Cancel
            </Button>,
            <Button
              key="unstake"
              type="primary"
              danger
              onClick={handleUnstake}
              loading={unstakeMutation.isLoading}
            >
              Unstake
            </Button>
          ]}
        >
          <Space direction="vertical" className="w-full">
            <div>
              <Text>Staked Balance: {formatNumber(balance?.staked_balance)} GOD</Text>
            </div>
            <Input
              type="number"
              placeholder="Enter amount to unstake"
              value={unstakeAmount}
              onChange={(e) => setUnstakeAmount(e.target.value)}
              addonAfter="GOD"
              min="0"
              max={balance?.staked_balance}
            />
            <Alert
              message="Unstaking will stop daily rewards for the unstaked amount"
              type="warning"
              showIcon
            />
          </Space>
        </Modal>
      </div>
    </div>
  );
};

export default Staking;